package com.taysear.parcel;

import java.util.ArrayList;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.NoResultException;

import com.taysear.parcel.domain.Permission;
import com.taysear.parcel.domain.Role;
import com.taysear.parcel.domain.RolePermission;
import com.taysear.parcel.domain.Route;
import com.taysear.parcel.domain.RouteDetail;
import com.taysear.parcel.domain.Substation;
import com.taysear.parcel.domain.User;
import com.taysear.parcel.domain.UserRole;
import com.vaadin.data.util.BeanItemContainer;
import com.vaadin.event.dd.acceptcriteria.SourceIs;
import com.vaadin.ui.Button;
import com.vaadin.ui.Form;
import com.vaadin.ui.FormLayout;
import com.vaadin.ui.HorizontalLayout;
import com.vaadin.ui.VerticalLayout;
import com.vaadin.ui.Window;
import com.vaadin.ui.Button.ClickEvent;
import com.vaadin.ui.themes.Reindeer;

public class AlterRouteDetailWindow extends Window {
	ParcelApplication app;
	int selectedRouteId;
	RouteDetailTable availableStationsTable;
	RouteDetailTable selectedRouteDetailsTable;
	List<Substation> selectedRouteDetailsList = new ArrayList<Substation>();
	List<Substation> availableRouteDetailsList = new ArrayList<Substation>();

	public AlterRouteDetailWindow(ParcelApplication app, int selectedRouteId) {
		super("Route details");
		this.app = app;
		this.selectedRouteId = selectedRouteId;
		
		Form form = new Form();
		form.setCaption(" ");
		form.setSizeFull();
		
		BeanItemContainer<Substation> availableSubstationsContainer = new BeanItemContainer<Substation>(Substation.class);
		BeanItemContainer<Substation> selectedRouteSubstationsContainer = new BeanItemContainer<Substation>(Substation.class);
		
		selectedRouteDetailsList = app.em.createQuery("SELECT rd.substation FROM RouteDetail rd Where rd.route.id = "+ selectedRouteId, Substation.class).getResultList();
		availableRouteDetailsList = app.em.createQuery("SELECT sub FROM Substation sub", Substation.class).getResultList();
		
		selectedRouteSubstationsContainer.addAll(selectedRouteDetailsList);
		for (Substation substation : availableRouteDetailsList) {
			if(!selectedRouteDetailsList.contains(substation))
				availableSubstationsContainer.addBean(substation);
		}
		
		String[] visibleColumns = new String[] {"Substation"};
		availableStationsTable = new RouteDetailTable("Available substations", availableSubstationsContainer, visibleColumns);
		selectedRouteDetailsTable = new RouteDetailTable("Selected route substations", selectedRouteSubstationsContainer, visibleColumns);
		availableStationsTable.initializeTable(new SourceIs(selectedRouteDetailsTable), availableSubstationsContainer);
		selectedRouteDetailsTable.initializeTable(new SourceIs(availableStationsTable), selectedRouteSubstationsContainer);
					 
		FormLayout formLayout = (FormLayout) form.getLayout();
		HorizontalLayout horizontalLayout = new HorizontalLayout();
		horizontalLayout.setSpacing(true);
		horizontalLayout.addComponent(availableStationsTable);
		horizontalLayout.addComponent(selectedRouteDetailsTable);
		formLayout.addComponent(horizontalLayout);
		
		Button save = new Button("Save", new Button.ClickListener() {
			@Override
			public void buttonClick(ClickEvent event) {
				saveRouteDetails();	
			}
		});
		save.setStyleName(Reindeer.BUTTON_SMALL);
		Button close = new Button("Close", new Button.ClickListener() {
			@Override
			public void buttonClick(ClickEvent event) {
				Window window = (Window) event.getButton().getParent().getParent().getParent().getParent();
				window.getParent().removeWindow(window);
			}
		});
		close.setStyleName(Reindeer.BUTTON_SMALL);
		form.getFooter().addComponent(save);
		form.getFooter().addComponent(close);
		
    	center();
    	setModal(true);
		VerticalLayout verticalLayout = (VerticalLayout) getContent();
		verticalLayout.setMargin(true);
        verticalLayout.setSpacing(true);
		verticalLayout.setSizeUndefined();
    	verticalLayout.addComponent(form);
	}
	
	private void saveRouteDetails() {
		EntityManager em = app.em;
		List<Substation> add = new ArrayList<Substation>();
		try{
			em.getTransaction().begin();
			
			BeanItemContainer<Substation> selectedSubstations = (BeanItemContainer<Substation>) selectedRouteDetailsTable.getContainerDataSource();
			Route selectedRoute = app.em.find(Route.class, selectedRouteId);
			List<Substation> selectedRouteDetailSubstationsList = app.em.createQuery("SELECT rd.substation FROM RouteDetail rd Where rd.route.id = "+ selectedRouteId, Substation.class).getResultList();
			List<RouteDetail> selectedRouteDetailsList = app.em.createQuery("SELECT rd FROM RouteDetail rd Where rd.route.id = "+ selectedRouteId, RouteDetail.class).getResultList();
			
			List<Substation> remove = new ArrayList<Substation>();
			remove.addAll(selectedRouteDetailSubstationsList);
			
			for (Substation p : selectedSubstations.getItemIds()) {
				if(!selectedRouteDetailSubstationsList.contains(p))
					add.add(p);
				else
					remove.remove(p);
			}
			
			for (Substation sub : add) {
				RouteDetail routeDetail = new RouteDetail();
				routeDetail.setRoute(selectedRoute);
				routeDetail.setSubstation(sub);
				routeDetail.setIsStartEnd(false);
				em.persist(routeDetail);
			}
			for (Substation sub : remove) {
				for (RouteDetail rd : selectedRouteDetailsList) {
					if(sub.getSubstationId() == rd.getSubstation().getSubstationId()) {
						RouteDetail routeDetail = em.find(RouteDetail.class, rd.getId());
						if(!routeDetail.getIsStartEnd())
							em.remove(routeDetail);
					}
				}
			}
			
			em.getTransaction().commit();
			app.showNotification("Route detail successfully saved.");
		} catch (Exception e) {
			app.showNotification("Oooopss something whent wrong !!..");
			em.getTransaction().rollback();
			e.printStackTrace();
		}
	}
}
